﻿using System;
using GpgCore.Corporations;
using GpgCore.Maps;
using GpgCore.Products;

namespace GpgCore.MapItems
{
    public class Mine : MapItem
    {
        public MiningScheme Scheme;
        public float ActualWorkers;
        public int NeedWorkers
        {
            get { return Scheme.WorkersPerLevel*Level; }
        }
        public int Level = 1;
        public float Productivity;
        public float WorkerPayment;

        public Corporation OwnCorporation;
        public CityOffice OwnOffice
        {
            get
            {
                if (BelongsToCity == null)
                    return null;
                CityOffice result;
                return BelongsToCity.CityOffices.TryGetValue(OwnCorporation, out result) ? result : null;
            }
        }

        public Mine(PlanetMapCell mapCell, MiningScheme scheme, Corporation ownCorporation) : base(mapCell)
        {
            OwnCorporation = ownCorporation;
            Scheme = scheme;
            ItemType = MapItemType.Farm;

            OwnOffice.Mines.AddDistinct(this);
        }

        public override void StartNextTurn()
        {
            HireWorkers();
            base.StartNextTurn();
        }
        public override void EndNextTurn()
        {
            GetMyWorkers();
            CalcProductivity();
            DoMining();
            base.EndNextTurn();
        }

        private void GetMyWorkers()
        {
            ActualWorkers = (float) BelongsToCity.Exchanges[ProductType.Employees].GetMyProduct(this);
        }
        private void DoMining()
        {
            if (MapCell.Minerals == null)
                return;

            double farmProdCount = Scheme.MinedPerWorker*Level*Scheme.WorkersPerLevel*Productivity;
            if (MapCell.Minerals.Count < farmProdCount)
                farmProdCount = MapCell.Minerals.Count;
            MapCell.Minerals.Count -= (long)farmProdCount;
            OwnOffice.Warehouse.Products[Scheme.OutputProduct].Count += (long) farmProdCount;
        }
        private void CalcProductivity()
        {
            Productivity = ActualWorkers/NeedWorkers;
            Productivity = Math.Min(Productivity, 2);
        }
        private void HireWorkers()
        {
            double payment = WorkerPayment*NeedWorkers;
            payment = OwnOffice.ExtractMoney(payment);
            BelongsToCity.Exchanges[ProductType.Employees].OpenPositionWithMoney(payment, this);
        }
    }
}
